const { verify } = require('jsonwebtoken');
function verifyToken(token, secret) {
  return new Promise(function(resolve, reject) {
    verify(token, secret, function(error, payload) {
      if (error) {
        reject(error);
      } else {
        resolve(payload);
      }
    });
  });
}
module.exports = app => {
  return async function(ctx, next) {
    const authorization = ctx.get('authorization');
    if (authorization) {
      try {
        const access_token = authorization.split(' ')[1];
        const { currentUser } = await verifyToken(access_token, app.config.jwtSecret);
        ctx.session.currentUser = currentUser;
        await next();
      } catch (error) {
        ctx.status = 401;
        ctx.body = 'access_token验证失败';
      }
    } else {
      ctx.status = 401;
      ctx.body = '没有access_token';
    }
  };
};
